package com.moter.demo01.juc.alllocks.optimisticlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class OptimisticLock {
    static class CAS{
        public static int getData() {
            return data;
        }

        public static void setData(int data) {
            CAS.data = data;
        }

        public static int getVersion() {
            return version;
        }

        public static void setVersion(int version) {
            CAS.version = version;
        }

        private static volatile int data =0;
        private static volatile int version=0;
        private static final Lock lock = new ReentrantLock();
        public boolean increment(){
            int tempVersion = version;
            int tempData = data+1;
            try {
                lock.lock();//保证加一是原子操作
                if(tempVersion==version){

                    data=tempData;
                    version=tempVersion+1;
                    return true;
                }else {

                    return false;
                }
            }finally {
                lock.unlock();
            }

        }
    }

    public static void main(String[] args) {
        CAS cas = new CAS();
        for (int i = 1; i <= 20; i++) {
            new Thread(()->{
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+cas.increment());
            },"Thread\t"+i).start();
        }
        while(Thread.activeCount()>2){}
        System.out.println("CAS.getData() = " + CAS.getData());
        System.out.println("CAS.getVersion() = " + CAS.getVersion());
    }
}
